package com.example.bootdemo.mq.consumer;

import com.alibaba.fastjson2.JSON;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * 消费者，监听消息,消费消息
 * 监听组：监听topic：监听tag（默认监听topic下所有）
 * 监听消费模式：默认负载均衡：CLUSTRRING（每个消息只发给一个消费者）、广播模式：BROADCASTING（发给所有消费者）
 */


@Component
@RocketMQMessageListener(topic = "${rocketmq.producer.topic1}", consumerGroup = "${rocketmq.consumer.group1}")
public class Consumer1 implements RocketMQListener<Message> {


    @Override
    public void onMessage(Message s) {
        System.out.println("消费者监听到消息1：>>> :" + JSON.toJSONString(s));
        System.out.println("消费者监听到消息1：>>> :" + s.getBody());
        byte[] body = s.getBody();


// 要注意的是，在转换回字符串时，必须使用与原始字符串相同的字符集
        String convertedString = null; // 指定字符集为UTF-8
        try {
            convertedString = new String(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        System.out.println(convertedString); // 输出: Hello, World!

    }
}
